// pages/vote/new/new.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name: "",
    vote_publish: false,
    start_date: '2018-01-01',
    start_time: '12:00',
    end_date: '2018-01-01',
    end_time: '12:00',
    address: "",
    student: "",
    levels_num: "",
    detail: "",
    status: "0",
    all: [
      [
        [''],
        ['']
      ]
    ],
    radioCheckVal: 'level',
    exam: '',
    teachers: {}
  },

  onShow: function() {
    var that = this
    if (that.data.exam != '') {
      //获得某一次验收的详情
      console.log(that.data.exam)
      wx.request({
        url: getApp().globalData.my_server + "/mark/get_details_of_an_exam",
        data: {
          id: that.data.exam,
        },
        method: "POST",
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        success: function(res) {
          console.log(res)
          if (res.data.error_no == 2) {
            wx.showModal({
              title: '哎呀～',
              content: res.data.error_msg,
              success: function(res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          } else if (res.data.error_no == 0) {
            var teachers = res.data.exam.teachers.split(",").map((group) => {
              return group.split("/").map((person) => {
                return person.split(":")
              })
            })

            var classes = res.data.exam.classes.split(",").map((group) => {
              return group.split("/")
            })

            var teachers_temp = {}
            for (var i = 0; i < teachers.length; i++) {
              for (var j = 0; j < teachers[i].length; j++) {
                teachers_temp[teachers[i][j][0]] = teachers[i][j][1]
              }
            }

            var all_temp = []
            for (var m = 0; m < teachers.length; m++) {
              var group_temp = [
                [],
                []
              ]

              for (var n = 0; n < teachers[m].length; n++) {
                group_temp[0].push(teachers[m][n][0])
              }
              for (var k = 0; k < classes[m].length; k++) {
                group_temp[1].push(classes[m][k])
              }

              all_temp.push(group_temp)
            }

            that.setData({
              name: res.data.exam.name,
              start_date: res.data.exam.start_time.split(" ")[0],
              start_time: res.data.exam.start_time.split(" ")[1],
              end_date: res.data.exam.stop_time.split(" ")[0],
              end_time: res.data.exam.stop_time.split(" ")[1],
              address: res.data.exam.address,
              teachers: teachers_temp,
              all: all_temp,
              status: res.data.exam.status,
              student: res.data.exam.student,
              radioCheckVal: res.data.exam.score_way,
              levels_num: res.data.exam.levels_num,
              detail: res.data.exam.detail
            })

          }
        },
        fail: function(res) {
          wx.showModal({
            title: '哎呀～',
            content: '获得验收详情失败',
            success: function(res) {
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
          console.log("fail!", res)
        },
        complete: function(res) {

        }
      })
    }

  },

  allplus: function() {
    var that = this
    var all_temp = that.data.all
    all_temp.push([
      [''],
      ['']
    ])
    that.setData({
      all: all_temp
    })
  },

  radioChange: function(e) {
    this.setData({
      radioCheckVal: e.detail.value
    })
  },


  plus: function(e) {
    var that = this

    var all_temp = that.data.all
    var group_index = e.currentTarget.dataset.group_index
    var content_index = parseInt(e.currentTarget.dataset.content_index)
    // console.log(typeof content_index).

    all_temp[group_index][content_index].push("")
    that.setData({
      all: all_temp
    })
  },

  substract: function(e) {
    var that = this
    var all_temp = that.data.all
    var group_index = e.currentTarget.dataset.group_index
    var content_index = e.currentTarget.dataset.content_index
    var id_index = e.currentTarget.dataset.id_index

    all_temp[group_index][content_index].splice(id_index, 1)

    if (all_temp[group_index][0].length == 0 && all_temp[group_index][1].length == 0) {
      all_temp.splice(group_index, 1)
    }

    that.setData({
      all: all_temp
    })
  },

  bindStartDateChange: function(e) {
    this.setData({
      start_date: e.detail.value
    })
  },

  bindEndDateChange: function(e) {
    this.setData({
      end_date: e.detail.value
    })
  },

  bindStartTimeChange: function(e) {
    this.setData({
      start_time: e.detail.value
    })
  },

  bindEndTimeChange: function(e) {
    this.setData({
      end_time: e.detail.value
    })
  },

  teacher_name: function(e) {
    var that = this
    var id = e.detail.value
    //查询老师名字
    wx.request({
      url: getApp().globalData.my_server + "/mark/get_name_by_id",
      data: {
        kind: "2",
        id: id
      },

      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function(res) {
        console.log(res)

        if (res.data.error_no == 2) {
          wx.showModal({
            title: '哎呀～',
            content: res.data.error_msg,
            success: function(res) {
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        } else if (res.data.error_no == 1) {
          console.log("成功")
          var teachers = that.data.teachers

          teachers[id] = res.data.doc.name
          that.setData({
            teachers: teachers
          })
        }
      },

    })
  },

  content_input: function(e) {
    var that = this
    var all_temp = that.data.all
    var group_index = e.currentTarget.dataset.group_index
    var content_index = e.currentTarget.dataset.content_index
    var id_index = e.currentTarget.dataset.id_index
    var title = e.detail.value
    all_temp[group_index][content_index][id_index] = title

    this.setData({
      all: all_temp
    })
  },

  formSubmit: function(e) {

    var that = this
    var list_obj = e.detail.value

    that.setData({
      vote_publish: true
    })
    wx.showLoading({
      title: '发布中',
    })

    console.log(list_obj)
    for (var item in list_obj) {
      if (list_obj[item] == "" && item != "levels_num") {
        wx.hideLoading()
        that.setData({
          vote_publish: false
        })
        wx.showModal({
          title: '哎呀～',
          content: "有的选项没有填呢～",
          success: function(res) {
            if (res.confirm) {
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
        return
      }
    }

    if (list_obj["score_way"] == "level" && isNaN(parseInt(list_obj["levels_num"]))) {
      wx.hideLoading()
      that.setData({
        vote_publish: false
      })
      wx.showModal({
        title: '哎呀～',
        content: "分级数目必须为整数",
        success: function(res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return
    }

    var exam = that.data.exam
    var all_temp = that.data.all
    var group_length = all_temp.length
    var classes = ""
    var teachers = ""

    for (var i = 0; i < group_length; i++) {
      for (var j = 0; j < all_temp[i][0].length; j++) {
        teachers += all_temp[i][0][j] + ":" + that.data.teachers[all_temp[i][0][j]]

        if (j == all_temp[i][0].length - 1 && i != group_length - 1) {
          teachers += ","
        } else if (j != all_temp[i][0].length - 1) {
          teachers += "/"
        }
      }


      for (var k = 0; k < all_temp[i][1].length; k++) {
        classes += all_temp[i][1][k]

        if (k == all_temp[i][1].length - 1 && i != group_length - 1) {
          classes += ","
        } else if (k != all_temp[i][1].length - 1) {
          classes += "/"
        }
      }
    }

    if (e.detail.value.levels_num == "") {
      e.detail.value.levels_num = '-1'
    }

    console.log(
      "name:", e.detail.value.subject,
      "start_time:", e.detail.value.start_date + " " + e.detail.value.start_time,
      "stop_time:", e.detail.value.end_date + " " + e.detail.value.end_time,
      "address:", e.detail.value.address,
      "student:", e.detail.value.student,
      "teachers:", teachers,
      "classes:", classes,
      "score_way:", e.detail.value.score_way,
      'levels_num:', e.detail.value.levels_num,
      "detail:", e.detail.value.detail,
      "status:", e.detail.value.status
    )

    if (that.data.exam == '') {
      //创建验收
      wx.request({
        url: getApp().globalData.my_server + "/mark/release_exam",
        data: {
          name: e.detail.value.subject,
          start_time: e.detail.value.start_date + " " + e.detail.value.start_time,
          stop_time: e.detail.value.end_date + " " + e.detail.value.end_time,
          address: e.detail.value.address,
          student: e.detail.value.student,
          teachers: teachers,
          classes: classes,
          score_way: e.detail.value.score_way,
          levels_num: e.detail.value.levels_num,
          detail: e.detail.value.detail,
          status: e.detail.value.status
        },

        method: "POST",
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        success: function(res) {
          console.log(res)

          if (res.data.error_no == 2) {
            wx.hideLoading()
            that.setData({
              vote_publish: false
            })
            wx.showModal({
              title: '哎呀～',
              content: res.data.error_msg,
              success: function(res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          } else if (res.data.error_no == 0) {
            console.log(res)
            wx.hideLoading()
            that.setData({
              vote_publish: false
            })
            console.log("成功")
            wx.navigateBack({
              delta: 1
            })
          }
        },

      })
    } else {
      //更新验收信息
      wx.request({
        url: getApp().globalData.my_server + "/mark/update_details",
        data: {
          exam_id: that.data.exam,
          name: e.detail.value.subject,
          start_time: e.detail.value.start_date + " " + e.detail.value.start_time,
          stop_time: e.detail.value.end_date + " " + e.detail.value.end_time,
          address: e.detail.value.address,
          student: e.detail.value.student,
          teachers: teachers,
          classes: classes,
          score_way: e.detail.value.score_way,
          levels_num: e.detail.value.levels_num,
          detail: e.detail.value.detail,
          status: e.detail.value.status
        },

        method: "POST",
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        success: function (res) {
          console.log(res)

          if (res.data.error_no == 2) {
            wx.hideLoading()
            that.setData({
              vote_publish: false
            })
            wx.showModal({
              title: '哎呀～',
              content: res.data.error_msg,
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          } else if (res.data.error_no == 0) {
            console.log(res)
            wx.hideLoading()
            that.setData({
              vote_publish: false
            })
            console.log("成功")
            wx.navigateBack({
              delta: 1
            })
          }
        },

      })
    }

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this
    that.setData({
      exam: options.examId
    })

  },


})